package com.maomao.time;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/**
 * Created by admin on 2018/5/10.
 */
public class DateTime {
    public static void main(String[] args) throws ParseException {
        DateTime dt = new DateTime();

        Date date = new SimpleDateFormat("yyyy-MM").parse("2008-02");
        date = dt.lastDayOfMonth("2008-02");
        System.out.println (new SimpleDateFormat("yyyy-MM-dd").format(date));

        date = new SimpleDateFormat("yyyy-MM-dd").parse("2008-02-14");
        date = dt.lastDayOfMonth2(date);
        System.out.println (new SimpleDateFormat("yyyy-MM-dd").format(date));

        date = new SimpleDateFormat("yyyy-MM-dd").parse("2008-02-14");
        date = dt.lastDayOfMonth3(date);
        System.out.println (new SimpleDateFormat("yyyy-MM-dd").format(date));

        date = new SimpleDateFormat("yyyy-MM-dd").parse("2008-02-14");
        date = dt.lastDayOfMonth4(date);
        System.out.println (new SimpleDateFormat("yyyy-MM-dd").format(date));
    }

    public Date lastDayOfMonth(String time) {
        Date date = null;
        try {
            date = new SimpleDateFormat("yyyy-MM").parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.set(Calendar.DAY_OF_MONTH, 1);
        cal.roll(Calendar.DAY_OF_MONTH, -1);
        return cal.getTime();
    }

    public Date lastDayOfMonth2(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        int value = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
        cal.set(Calendar.DAY_OF_MONTH, value);
        return cal.getTime();
    }

    public Date lastDayOfMonth3(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.set(Calendar.DAY_OF_MONTH, 1);
        cal.add(Calendar.MONTH, 1);
        cal.add(Calendar.DATE, -1);
        return cal.getTime();
    }

    public Date lastDayOfMonth4(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        do {
            cal.add(Calendar.DATE, 1);
        }
        while (cal.get(Calendar.DATE) != 1);
        cal.add(Calendar.DATE, -1);
        return cal.getTime();
    }
}
